package com.rgsx.utils;

import com.rgsx.data.DataPool;
import com.rgsx.entiy.Position;
import com.rgsx.exception.OrderSelectEmptyException;
import com.rgsx.mapper.OrderMapper;
import com.rgsx.mapper.UserMapper;
import com.rgsx.vo.entiyVo.PosListItem;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

@Component
public class RedisPositionUtil {
    /**
     * 验证经纬度距离地址：经纬度距离计算 (hhlink.com)
     * 根据当前位置获取附近指定范围内的用户
     *
     * @param distance 指定范围 单位km ，可根据{@link Metrics} 进行设置
     * @param driverLng  用户经度
     * @param driverLat  用户纬度
     * @param redisTemplate 工具
     * @return
     */
    public static List<PosListItem> nearBySearch(double distance, double driverLng, double driverLat, RedisTemplate redisTemplate) {
        List<PosListItem> posList = new ArrayList<>();
        Distance distanceArg = new Distance(distance, Metrics.KILOMETERS);
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates().sortAscending();
        // 1.GEORADIUS获取附近范围内的信息
        GeoResults<RedisGeoCommands.GeoLocation<Object>> reslut =
                redisTemplate.opsForGeo().radius(DataPool.KEY, new Circle(new Point(driverLng, driverLat), distanceArg), args);
        //2.收集信息，存入list


        List<GeoResult<RedisGeoCommands.GeoLocation<Object>>> contents = reslut.getContent();
        //3.返回计算后的信息
        for (int i = 0; i < contents.size(); i++) {
            RedisGeoCommands.GeoLocation<Object> content = contents.get(i).getContent();

            String orderId = content.getName().toString();
            orderId = orderId.substring(orderId.indexOf(':') + 1);
            Point point = content.getPoint();
            Position position = new Position(point.getX(),point.getY());
            posList.add(new PosListItem(position,Long.valueOf(orderId)));
        }
        return posList;
    }

    public static boolean setGeoToRedis(RedisTemplate redisTemplate,Long orderId,Position position) {
        try {
            Long flag = redisTemplate.opsForGeo().add(DataPool.KEY,
                    new RedisGeoCommands.GeoLocation<>(
                            "order:" + orderId,
                            new Point(Double.parseDouble(position.getPositionLongitude()),
                                    Double.parseDouble(position.getPositionLatitude()))
                    )
            );
            //回滚
            if(flag == null || flag <= 0) return false;
            return true;
        } catch (Exception e) {
            return false;
        }


    }
}
